package com.alibaba.boot.netty;

import java.io.*;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;

public class NioServerTest {

    public static void main(String[] args) throws Exception{

        NioServerT();
    }

    public static void  alterFileContent() throws Exception{
        RandomAccessFile randomAccessFile = new RandomAccessFile("D:\\files.txt","rw");
        FileChannel fileChannel =randomAccessFile.getChannel();
        MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE,0,5);
        mappedByteBuffer.put(0,(byte)('H'));
        mappedByteBuffer.put(3, (byte) ('9'));
        randomAccessFile.close();

    }

    public static void  intBufferTest(){
        IntBuffer intBuffer =IntBuffer.allocate(5);
        intBuffer.put(1);
        intBuffer.put(2);
        intBuffer.put(3);
        intBuffer.put(4);
        intBuffer.flip();
        intBuffer.limit(2);
        while (intBuffer.hasRemaining()){
            System.out.println(intBuffer.get());
        }
    }

    public static void  fileChannelInputPutTest() throws Exception{

        FileInputStream fileInputStream = new FileInputStream("D:\\files.txt");
        FileChannel fileChannel = fileInputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(fileInputStream.available());
        fileChannel.read(byteBuffer);
        byteBuffer.flip();

        System.out.println(new String(byteBuffer.array()));
        fileInputStream.close();
    }

    public static void fileChannelOutPutTest() throws IOException {
        String str="hello wrorld";
        FileOutputStream fileOutputStream =new FileOutputStream("D:\\files.txt");
        FileChannel fileChannel = fileOutputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        byteBuffer.put(str.getBytes(StandardCharsets.UTF_8));
        byteBuffer.flip();
        fileChannel.write(byteBuffer);
        fileOutputStream.close();
    }

    public  static void  fileTransferToAnotherFile() throws Exception{

        FileOutputStream fileOutputStream =new FileOutputStream("D:\\files2.txt");

       FileChannel outPutChannel = fileOutputStream.getChannel();

        FileInputStream fileInputStream = new FileInputStream("D:\\files.txt");
        FileChannel inputChannel = fileInputStream.getChannel();

        ByteBuffer byteBuffer =ByteBuffer.allocate(512);

        while (true){

            //读进来
            byteBuffer.clear();
            int read =inputChannel.read(byteBuffer);
            if (read == -1){
                break;
            }
            //翻转
            byteBuffer.flip();
            //写进去
            outPutChannel.write(byteBuffer);
        }


        fileInputStream.close();
        fileOutputStream.close();

    }

    public static void  nioServerStart() throws Exception{

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);
        serverSocketChannel.socket().bind(inetSocketAddress);
        ByteBuffer[] buffers = new ByteBuffer[2];

        buffers[0] = ByteBuffer.allocate(5);
        buffers[1] =ByteBuffer.allocate(3);


        SocketChannel socketChannel = serverSocketChannel.accept();

        while (true){

            int byteRead = 0;
            while (byteRead < 8){
                long l =socketChannel.read(buffers);
                byteRead+=1;

            }
            Arrays.asList(buffers).forEach(byteBuffer -> byteBuffer.flip());

            int byteWrite=0;
            while (byteWrite<8){
                long l = socketChannel.write(buffers);
                byteWrite+=1;
            }
            Arrays.asList(buffers).forEach(byteBuffer -> byteBuffer.clear());
        }
    }



    public static void  NioServerT() throws Exception{

        ServerSocketChannel serverSocketChannel =ServerSocketChannel.open();
        Selector selector =Selector.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true){
            if (selector.select(1000) == 0){
                System.out.println("服务器无事件发生。。。。。");
                continue;
            }
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()){

                SelectionKey selectionKey =    keyIterator.next();

                if (selectionKey.isAcceptable()){
                    System.out.println("客户端连接成功");
                   SocketChannel socketChannel =  serverSocketChannel.accept();
                   socketChannel.configureBlocking(false);
                   socketChannel.register(selector,SelectionKey.OP_READ,ByteBuffer.allocate(1024));
                }else if (selectionKey.isReadable()){
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    ByteBuffer byteBuffer = (ByteBuffer) selectionKey.attachment();
                    channel.read(byteBuffer);
                    System.out.println("from client:"+new String(byteBuffer.array()));
                }
                keyIterator.remove();

            }
        }
    }



}
